<template>
  <div class="box">
    <!-- 导入 -->
    <div class="export">
      <div class="upload">
        <el-upload class="upload-demo" :action="action" :headers="token" :on-success="handleUploadSuccess"
          :before-upload="beforeUpload" :show-file-list="false" :on-progress="ing">
          <el-button type="primary">导入IMEI编码</el-button>
        </el-upload>
      </div>
      <div>
        <template>
          <download-excel class="export-excel-wrapper" :data="excelForm" :fields="json_fields" :header="excelTitle"
            name="设备列表.xls">
            <!-- <el-button @click="handleExport" type="primary">导出设备</el-button> -->
            <el-button type="success" @click="getList(1)">刷新</el-button>
          </download-excel>
        </template>
      </div>
    </div>
    <!-- 表格 -->
    <el-table v-loading="loading" border style="width: 100%" :data="tableData">
      <el-table-column prop="id" label="#ID" align="center" width="50" />
      <el-table-column prop="imei" label="IMEI编码" align="center" show-overflow-tooltip />
      <el-table-column prop="status" label="使用状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === null ? 'info' :(scope.row.status===1 ? 'success' : 'primary' )"
            disable-transitions>{{ scope.row.status === null ? '未使用' :(scope.row.status === 1 ? '已绑定':'已解绑') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="itime" label="导入时间" align="center" width="170">
        <template slot-scope="scope">
          {{ timestampToTime(scope.row.itime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="260px">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status!==1" size="mini" type="danger" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 翻页 -->
    <el-pagination class="pagination" background layout="total,prev, pager, next" :total="total" :page-size="pageSize"
      @current-change="handleCurrentChange" />
  </div>
</template>
<script>
  import {
    imeiList,
    imeiDelete
  } from '@/api/device.js'
  import {
    unBinding
  } from '@/api/user.js'
  import {
    getToken
  } from '@/utils/auth'
  import store from '@/store'
  export default {
    data() {
      return {
        tableData: [],
        total: 0,
        pageSize: 10,
        currPage: 1,
        loading: false,
        loadingall: '',
        token: {
          'x-csrf-token': getToken()
        },
        action: process.env.VUE_APP_BASE_API + 'admin/import',
        // excel
        json_fields: {
          'ID': 'id',
          '设备别名': 'device_name',
          '添加时间': 'itime',
          '最近一次上报地址': 'address',
          '固件版本': 'version',
          '网卡状态': 'network_card',
          '设备编码': 'device_imei'
        },
        excelTitle: '所有设备列表',
        excelForm: []
      }
    },
    created() {
      this.getList(1)
    },
    methods: {
      // 列表
      getList(num) {
        this.loading = true
        imeiList({
          page: this.currPage,
          size: this.pageSize
        }).then(res => {
          this.loading = false
          this.tableData = res.data.list
          this.total = res.data.count
        })
      },
      // 当前页改变时触发 跳转其他页
      handleCurrentChange(val) {
        this.currPage = val
        this.getList(val)
      },
      // 删除
      handleDel(row) {
        var imei = row.imei
        this.$confirm('此操作将删除该IMEI，如要绑定设备，请重新添加该IMEI, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          imeiDelete({
            imei: imei
          }).then((res) => {
            if (res.code == 1) {
              this.$message.success('删除成功')
              // 刷新当前页
              this.getList(1)
            } else {
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      // 导入
      handleUploadSuccess(response, file, fileList) {
        // console.log(file)
        // console.log(response)
        if (response.code == 1) {
          this.$message.success('上传成功')
          this.getList(1)
        } else {
          this.$message.error(response.message)
        }
        this.loadingall.close()
        // 在这里可以使用axios等网络请求库将文件发送到后端
      },
      beforeUpload(file) {
        // console.log(file.type)
        const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        const isLt5M = file.size / 1024 / 1024 < 5
        if (!isXlsx) {
          this.$message.error('只能上传xlsx文件')
          return false
        }
        if (!isLt5M) {
          this.$message.error('上传文件大小不能超过 5 MB')
          return false
        }
        this.loadingall = this.$loading({
          lock: true,
          text: '⏫：文件上传中，请等待...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return true
      },
      timestampToTime(timestamp) {
        timestamp = timestamp || null
        const date = new Date(timestamp) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
        const Y = date.getFullYear() + '-'
        const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
        const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
        const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
        const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        return Y + M + D + h + m + s
      },
      ing(event, file, fileList) {
        console.log(event)
        console.log(file)
        console.log(fileList)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .box {
    margin: 20px 50px;
  }

  .button,
  .el-input {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .el-input {
    width: 200px;
    height: 50px;
    margin-right: 10px;
  }

  .export {
    display: flex;
  }

  .upload {
    margin-right: 10px;
    margin-bottom: 10px;
  }
</style>